#include <sys/select.h>
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char const *argv[])
{
    int ret;
    int maxNfds = 0;
    fd_set readfds;//文件描述符集合
    FD_ZERO(&readfds);
    FD_SET(0, &readfds);

    fd_set readfds_temp;
    FD_ZERO(&readfds_temp);
    FD_SET(0, &readfds_temp);
    struct timeval tv  = {3, 0};//设置超时时间为3s
    struct timeval timeout ;
    for (;;) {
        readfds_temp = readfds;
        timeout = tv;
        ret = select(maxNfds + 1, &readfds_temp, NULL, NULL, &timeout); //一旦超时， tv 会被修改
        // select 会每次将就绪的文件描述符拷贝到原集合中， 导致将readfds 置空
        if (ret == -1) {
            perror(" error select");
            exit(EXIT_FAILURE);
        } else if (ret == 0) { //超时返回
            perror(" error timeout");
        } else if (ret > 0) {
            if (FD_ISSET(0, &readfds_temp)) { // 判断文件 描述符0标准输入 是否在集合里， 如果在则表示就绪
                char buf[32] = {0};
                fgets(buf, sizeof(buf), stdin);
                printf("read from stdin: %s\n", buf);
            }
        }
    }
    return 0;
}
